package com.innovation.ic.im.end.base.service.im_erp9.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.RedisManager;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.im.end.base.mapper.im_erp9.GroupMessageMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.RefGroupAccountMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.RefGroupAccountOperationMapper;
import com.innovation.ic.im.end.base.model.im_erp9.GroupMessage;
import com.innovation.ic.im.end.base.model.im_erp9.RefGroupAccount;
import com.innovation.ic.im.end.base.model.im_erp9.RefGroupAccountOperation;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.pojo.constant.MessageContext;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.innovation.ic.im.end.base.service.im_erp9.GroupMessageService;
import com.innovation.ic.b1b.framework.util.DateUtils;
import com.innovation.ic.im.end.base.handler.im_erp9.ModelHandler;
import com.innovation.ic.im.end.base.value.config.PictureParamConfig;
import com.innovation.ic.im.end.base.vo.im_erp9.GroupMessageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * GroupMessage的具体实现类
 */
@Service
@Transactional
public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, GroupMessage> implements GroupMessageService {
    private static final Logger log = LoggerFactory.getLogger(GroupMessageServiceImpl.class);

    @Resource
    private PictureParamConfig pictureParamConfig;

    @Resource
    private GroupMessageMapper groupMessageMapper;

    @Resource
    private RefGroupAccountMapper refGroupAccountMapper;

    @Resource
    private RedisManager redisManager;

    @Resource
    private RefGroupAccountOperationMapper refGroupAccountOperationMapper;

    @Resource
    private ModelHandler modelHandler;

    /**
     * 保存GroupMessage对象
     *
     * @param groupMessage
     */
    @Override
    public ServiceResult<Integer> saveGroupMessage(GroupMessage groupMessage) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();
        groupMessageMapper.insert(groupMessage);

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(groupMessage.getId());
        return serviceResult;
    }

    /**
     * 获取用户的聊天记录，并按照创建时间降序排列，支持分页显示
     *
     * @param fromUserAccount
     * @param pageSize
     * @param pageNo
     * @return
     */
    @Override
    public ServiceResult<Page> page(String fromUserAccount, Integer pageSize, Integer pageNo) {
        ServiceResult<Page> serviceResult = new ServiceResult<>();

        Page<GroupMessage> pageParam = new Page<>(pageSize, pageNo);
        QueryWrapper<GroupMessage> groupMessageQueryWrapper = new QueryWrapper<>();
        groupMessageQueryWrapper.eq("from_user_account", fromUserAccount);
        groupMessageQueryWrapper.orderByDesc("create_time");
        Page<GroupMessage> page = baseMapper.selectPage(pageParam, groupMessageQueryWrapper);

        log.info("分页查询结果:" + page.getRecords());
        log.info("分页总共的数据量:" + page.getTotal());
        log.info("分页总共的页码数:" + page.getPages());

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(page);
        return serviceResult;
    }

    /**
     * 获取某个群组的聊天记录，并按照创建时间降序排列，支持分页显示
     *
     * @param groupId
     * @param fromUserAccount
     * @param pageSize
     * @param pageNo
     * @param type
     * @return
     */
    @Override
    public ServiceResult<List<GroupMessage>> redisPage(String groupId, String fromUserAccount, Integer pageSize, Integer pageNo, Integer type, Integer timeOut) {
        ServiceResult<List<GroupMessage>> serviceResult = new ServiceResult<>();
        int start = pageSize * (pageNo - 1);

        // 内容不可见时间
        Date contentInvisibleTime = getContentInvisibleTimeByGroupAccountId(groupId, fromUserAccount);

        // 从redis中获取需要的数据
        Set<String> stringSet = getRedisDataByParam(start, pageSize, groupId, contentInvisibleTime, timeOut);

        if (stringSet == null || stringSet.size() == 0) {
            List<GroupMessage> groupMessagesList = new ArrayList<GroupMessage>();
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(groupMessagesList);
            return serviceResult;
        }

        //判断type 是什么返回的数据不同
        //type为0情况 全部
        if (type.equals(MessageType.ALL)) {
            List<GroupMessage> list = modelHandler.toGroupMessageList(stringSet, fromUserAccount);
            for (int i = 0; i < list.size(); i++) {
                GroupMessage groupMessage = list.get(i);
                if (groupMessage.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                    String substring = groupMessage.getFilePath().substring(groupMessage.getFilePath().lastIndexOf("/") + 1);
                    list.get(i).setFilePath(substring);
                }
            }
            // 处理list中的图片数据
            handListPictureData(list);
            //进行list集合排序（升序）
            list.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(list);
            return serviceResult;
        } else if (type.equals(MessageType.FILE)) {//type为2 文件
            //序列化数据
            List<GroupMessage> groupMessageList = modelHandler.toGroupMessageList(stringSet, fromUserAccount);
            //创建一个空的集合 把属于文件(图片)的数据存入
            List<GroupMessage> newGroupMessageList = new ArrayList<GroupMessage>();
            for (int i = 0; i < groupMessageList.size(); i++) {
                //获取当中每一个type进行判断 如果是文件就返回
                GroupMessage groupMessage = groupMessageList.get(i);
                if (groupMessage.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                    String substring = groupMessage.getFilePath().substring(groupMessage.getFilePath().lastIndexOf("/") + 1);
                    groupMessageList.get(i).setFilePath(substring);
                    newGroupMessageList.add(groupMessageList.get(i));
                }
            }
            //进行list集合排序（升序）
            newGroupMessageList.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newGroupMessageList);
            return serviceResult;

        } else { //type为3 图片
            //序列化数据
            List<GroupMessage> groupMessageList = modelHandler.toGroupMessageList(stringSet, fromUserAccount);
            //创建一个空的集合 把属于文件(图片)的数据存入
            List<GroupMessage> newGroupMessageList = new ArrayList<GroupMessage>();
            for (int i = 0; i < groupMessageList.size(); i++) {
                //获取当中每一个type进行判断 如果是图片就返回
                Integer groupMessagesType = groupMessageList.get(i).getType();
                if (groupMessagesType.equals(MessageType.PICTURE)) {
                    GroupMessage groupMessage = groupMessageList.get(i);
                    if (!Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                        groupMessage.setFilePath(pictureParamConfig.getUrlprefix() + groupMessage.getFilePath());
                    }
                    newGroupMessageList.add(groupMessage);
                }
            }
            //进行list集合排序（升序）
            newGroupMessageList.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newGroupMessageList);
            return serviceResult;
        }
    }

    /**
     * 处理list中的图片数据
     *
     * @param list 结果list
     */
    private void handListPictureData(List<GroupMessage> list) {
        if (list != null && list.size() > 0) {
            for (GroupMessage groupMessage : list) {
                if (groupMessage.getType().intValue() == MessageType.PICTURE && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                    groupMessage.setFilePath(pictureParamConfig.getUrlprefix() + groupMessage.getFilePath());
                }
            }
        }
    }

    /**
     * 根据参数type和content（模糊查询），获取默认群组的聊天记录，并按照创建时间降序排列，支持分页显示
     *
     * @return
     */
    @Override
    public ServiceResult<List<GroupMessage>> redisLikePage(GroupMessageVo groupMessageVo, Integer timeout) {
        ServiceResult<List<GroupMessage>> serviceResult = new ServiceResult<>();
        int start = groupMessageVo.getPageSize() * (groupMessageVo.getPageNo() - 1);

        // 内容不可见时间
        Date contentInvisibleTime = getContentInvisibleTimeByGroupAccountId(groupMessageVo.getGroupId(), groupMessageVo.getFromUserAccount());

        // 从redis中获取需要的数据
        Set<String> stringSet = getRedisDataByParam(start, groupMessageVo.getPageSize(), groupMessageVo.getGroupId(), contentInvisibleTime, timeout);

        if (stringSet == null || stringSet.size() == 0) {
            List<GroupMessage> groupMessagesList = new ArrayList<GroupMessage>();
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(groupMessagesList);
            return serviceResult;
        }
        //数据序列化
        List<GroupMessage> groupMessageList = modelHandler.toGroupMessageList(stringSet, groupMessageVo.getFromUserAccount());
        //创建一个空的集合进行存数据
        List<GroupMessage> newGroupMessagesList = new ArrayList<>();
        //传递参数是否带内容如果有则模糊查询，没有则不需要
        if (StringUtils.isEmpty(groupMessageVo.getContent())) {
            for (int i = 0; i < groupMessageList.size(); i++) {
                GroupMessage groupMessage = groupMessageList.get(i);

                // 撤回、系统的消息忽略
                if(groupMessage.getRetractionTime() != null || groupMessage.getType().equals(MessageType.SYS_MSG) || groupMessage.getType().equals(MessageType.UPDATE_USER_GROUP_NAME_SYS_MSG)){
                    continue;
                }

                //根据type不同返回不同的数据
                if (groupMessageVo.getType().equals(MessageType.ALL)) {
                    if (groupMessage.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                        String substring = groupMessage.getFilePath().substring(groupMessage.getFilePath().lastIndexOf("/") + 1);
                        groupMessage.setFilePath(substring);
                    }
                    if (groupMessage.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                        groupMessage.setFilePath(pictureParamConfig.getUrlprefix() + groupMessage.getFilePath());
                    }
                    newGroupMessagesList.add(groupMessage);
                    continue;
                }
                if (groupMessageVo.getType().equals(MessageType.FILE) && groupMessage.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                    String substring = groupMessage.getFilePath().substring(groupMessage.getFilePath().lastIndexOf("/") + 1);
                    groupMessage.setFilePath(substring);
                    newGroupMessagesList.add(groupMessage);
                    continue;
                }
                if (groupMessageVo.getType().equals(MessageType.PICTURE) && groupMessage.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                    groupMessage.setFilePath(pictureParamConfig.getUrlprefix() + groupMessage.getFilePath());
                    newGroupMessagesList.add(groupMessage);
                    continue;
                }
            }
            //进行list集合排序（升序）
            newGroupMessagesList.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newGroupMessagesList);
            return serviceResult;
        } else {
            //模糊不区分大小
            Pattern pattern = Pattern.compile(groupMessageVo.getContent(), Pattern.CASE_INSENSITIVE);
            for (int i = 0; i < groupMessageList.size(); i++) {
                GroupMessage groupMessage = groupMessageList.get(i);

                // 撤回、系统的消息忽略
                if(groupMessage.getRetractionTime() != null || groupMessage.getType().equals(MessageType.SYS_MSG) || groupMessage.getType().equals(MessageType.UPDATE_USER_GROUP_NAME_SYS_MSG)){
                    continue;
                }

                if (!Strings.isNullOrEmpty(groupMessage.getContent()) || !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                    Boolean result = Boolean.FALSE;

                    // 文字匹配聊天内容
                    if (!Strings.isNullOrEmpty(groupMessage.getContent())) {
                        Matcher contentMatcherContent = pattern.matcher(groupMessage.getContent());
                        result = contentMatcherContent.find();
                    }

                    // 图片、文件匹配文件名
                    if (!Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                        Matcher filepathMatcherContent = pattern.matcher(groupMessage.getFilePath());
                        result = filepathMatcherContent.find();
                    }

                    //进行根据参数type和content（模糊查询）
                    if (result) {
                        // 根据type不同返回不同的数据
                        if (groupMessageVo.getType().equals(MessageType.ALL)) {
                            if (groupMessage.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                                String substring = groupMessage.getFilePath().substring(groupMessage.getFilePath().lastIndexOf("/") + 1);
                                groupMessage.setFilePath(substring);
                            }
                            if (groupMessage.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessage.getFilePath())) {
                                // 图片路径前要拼接url前缀
                                groupMessage.setFilePath(pictureParamConfig.getUrlprefix() + groupMessage.getFilePath());
                            }
                            newGroupMessagesList.add(groupMessage);
                            continue;
                        }
                        if (groupMessageVo.getType().equals(MessageType.FILE) && groupMessage.getType().equals(MessageType.FILE)) {
                            newGroupMessagesList.add(groupMessage);
                        }
                    }
                }
            }
            //进行list集合排序（升序）
            newGroupMessagesList.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(newGroupMessagesList);
            return serviceResult;
        }

    }

    /**
     * 根据参数id、initRow和direction，获取默认群组的某个聊天记录的上下文记录，并按照创建时间降序排列，分别支持向上和向下分页显示
     * @param id
     * @param fromUserAccount
     * @param initRow
     * @param direction
     * @param pageSize
     * @param pageNo
     * @return
     */
    @Override
    public ServiceResult<List<GroupMessage>> redisContextPage(String id, String fromUserAccount, Integer initRow, Integer direction, Integer pageSize, Integer pageNo, Integer timeout) {
        ServiceResult<List<GroupMessage>> serviceResult = new ServiceResult<>();
        int start = pageSize * (pageNo - 1);

        // 根据id获取groupMessage表数据
        GroupMessage groupMessage = groupMessageMapper.selectById(id);

        // 内容不可见时间
        Date contentInvisibleTime = getContentInvisibleTimeByGroupAccountId(groupMessage.getGroupId(), fromUserAccount);

        // 从redis中获取需要的数据
        Set<String> stringSet = getRedisDataByParam(start, pageSize, groupMessage.getGroupId(), contentInvisibleTime, timeout);

        if (stringSet == null ||stringSet.size() == 0){
            List<GroupMessage> groupMessagesList = new ArrayList<>();
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(groupMessagesList);
            return serviceResult;
        }
        //数据序列化
        List<GroupMessage> groupMessageList = modelHandler.toGroupMessageList(stringSet, fromUserAccount);
        //根据当前数据向下展示
        if (direction.equals(MessageContext.DOWN)) {
            List<GroupMessage> groupMessageDownList;
            if (groupMessageList.size() > initRow) {
                groupMessageDownList = groupMessageList.subList(initRow, groupMessageList.size());
                for (int i = 0; i < groupMessageDownList.size(); i++) {
                    GroupMessage groupMessageData = groupMessageDownList.get(i);
                    if (groupMessageData.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        String substring = groupMessageData.getFilePath().substring(groupMessageData.getFilePath().lastIndexOf("/") + 1);
                        groupMessageDownList.get(i).setFilePath(substring);
                    }
                    if (groupMessageData.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        groupMessageData.setFilePath(pictureParamConfig.getUrlprefix() + groupMessageData.getFilePath());
                    }
                    groupMessageDownList.set(i, groupMessageData);
                }
            } else {
                groupMessageDownList = groupMessageList;
                for (int i = 0; i < groupMessageDownList.size(); i++) {
                    GroupMessage groupMessageData = groupMessageDownList.get(i);
                    if (groupMessageData.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        String substring = groupMessageData.getFilePath().substring(groupMessageData.getFilePath().lastIndexOf("/") + 1);
                        groupMessageDownList.get(i).setFilePath(substring);
                    }
                    if (groupMessageData.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        groupMessageData.setFilePath(pictureParamConfig.getUrlprefix() + groupMessageData.getFilePath());
                    }
                    groupMessageDownList.set(i, groupMessageData);
                }
            }
            //进行list集合排序（升序）
            groupMessageDownList.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(groupMessageDownList);
            return serviceResult;
        } else {
            //根据当前数据向上展示UPWARD
            List<GroupMessage> groupMessageUpwardList;
            if (groupMessageList.size() > initRow) {
                groupMessageUpwardList = groupMessageList.subList(0, initRow + 1);
                for (int i = 0; i < groupMessageUpwardList.size(); i++) {
                    GroupMessage groupMessageData = groupMessageUpwardList.get(i);
                    if (groupMessageData.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        String substring = groupMessageData.getFilePath().substring(groupMessageData.getFilePath().lastIndexOf("/") + 1);
                        groupMessageUpwardList.get(i).setFilePath(substring);
                    }
                    if (groupMessageData.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        groupMessageData.setFilePath(pictureParamConfig.getUrlprefix() + groupMessageData.getFilePath());
                    }
                    groupMessageUpwardList.set(i, groupMessageData);
                }
            } else {
                groupMessageUpwardList = groupMessageList;
                for (int i = 0; i < groupMessageUpwardList.size(); i++) {
                    GroupMessage groupMessageData = groupMessageUpwardList.get(i);
                    if (groupMessageData.getType().equals(MessageType.FILE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        String substring = groupMessageData.getFilePath().substring(groupMessageData.getFilePath().lastIndexOf("/") + 1);
                        groupMessageUpwardList.get(i).setFilePath(substring);
                    }
                    if (groupMessageData.getType().equals(MessageType.PICTURE) && !Strings.isNullOrEmpty(groupMessageData.getFilePath())) {
                        // 图片路径前要拼接url前缀
                        groupMessageData.setFilePath(pictureParamConfig.getUrlprefix() + groupMessageData.getFilePath());
                    }
                    groupMessageUpwardList.set(i, groupMessageData);
                }
            }
            //进行list集合排序（升序）
            groupMessageUpwardList.sort(Comparator.comparing(GroupMessage::getCreateTime));
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(groupMessageUpwardList);
            return serviceResult;
        }
    }

    /**
     * 将group_message表中的数据导入redis
     * @return 返回导入结果
     */
    @Override
    public ServiceResult<Boolean> importGroupMessageIntoRedis() {
        ServiceResult<Boolean> returnResult = new ServiceResult<>();

        List<GroupMessage> groupMessageList = findAllOrderByCreateTimeDesc();
        if (null != groupMessageList && groupMessageList.size() > 0) {
            log.info("开始导入group_message数据");
            for (int i = 0; i < groupMessageList.size(); i++) {
                GroupMessage groupMessage = groupMessageList.get(i);
                redisManager.zAdd(RedisStorage.GROUP_MESSAGE_PREFIX + groupMessage.getGroupId(),
                        JSON.toJSONString(groupMessageList.get(i)),
                        groupMessage.getCreateTime().getTime());
//                redisManager.expire(RedisStorage.GROUP_MESSAGE_PREFIX + groupMessage.getGroupId(), redisParamConfig.getTimeout());
            }
        }

        returnResult.setMessage(ServiceResult.SYNC_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }

    /**
     * 查询所有记录，按照创建时间降序排列
     * @return 返回查询结果
     */
    public List<GroupMessage> findAllOrderByCreateTimeDesc() {
        QueryWrapper<GroupMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据请求参数从redis中获取需要的数据
     *
     * @param start                指定开始位置
     * @param pageSize             查询数据数量
     * @param groupId              群组id
     * @param contentInvisibleTime 内容不可见时间
     * @return 返回查询结果
     */
    private Set<String> getRedisDataByParam(long start, long pageSize, String groupId, Date contentInvisibleTime, Integer timeout) {
        Set<String> stringSet;

        long startScore;
        long endScore = System.currentTimeMillis();

        // 获取指定时间前的时间
        Date leftDate = DateUtils.getLeftDateByTime(timeout);

        // 若用户设置了内容不可见时间，查询聊天记录时查询此时间及之后的数据，否则查询所有数据
        if (contentInvisibleTime != null) {
            // 判断内容不可见时间如果早于15天前的时间，则查询开始时间为15天前的时间
            if (contentInvisibleTime.compareTo(leftDate) < 0) {
                startScore = leftDate.getTime();
            } else {
                startScore = contentInvisibleTime.getTime();
            }
        } else {
            startScore = leftDate.getTime();
        }
        stringSet = redisManager.zReverseRangeByScore(RedisStorage.GROUP_MESSAGE_PREFIX + groupId, startScore, endScore, start, pageSize);
        return stringSet;
    }

    /**
     * 根据默认组id和账号id获取账号信息
     *
     * @param groupId   默认群组id
     * @param accountId 账号id
     * @return 返回账号信息
     */
    private RefGroupAccount getRefGroupAccountByGroupIdAccountId(String groupId, String accountId) {
        QueryWrapper<RefGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.GROUP_ID_FIELD, groupId);
        queryWrapper.eq(Constants.ACCOUNT_ID_FIELD, accountId);
        return refGroupAccountMapper.selectOne(queryWrapper);
    }

    /**
     * 获取根据查询条件未获取到用户信息时的返回结果
     *
     * @param serviceResult   结果
     * @param groupId         默认群组id
     * @param fromUserAccount 发送消息的用户账号
     * @return 返回结果
     */
    private ServiceResult<List<GroupMessage>> returnQueryFaultResult(ServiceResult<List<GroupMessage>> serviceResult, String groupId, String fromUserAccount) {
        List<GroupMessage> groupMessageList = new ArrayList<>();
        serviceResult.setMessage(ServiceResult.SELECT_FAIL);
        serviceResult.setSuccess(Boolean.FALSE);
        serviceResult.setMessage("根据默认群组:{" + groupId + "},用户账号:{" + fromUserAccount + "}查询用户数据失败,请重试");
        serviceResult.setResult(groupMessageList);
        return serviceResult;
    }

    /**
     * 根据默认组id和账号id获取内容不可见时间
     *
     * @param groupId
     * @param userName
     * @return
     */
    private Date getContentInvisibleTimeByGroupAccountId(String groupId, String userName) {
        // 内容不可见时间
        Date contentInvisibleTime = null;

        // 根据默认群组id、账号id查询账号和群组的操作表数据
        RefGroupAccountOperation refGroupAccountOperation = refGroupAccountOperationMapper.selectDataByGroupAccountUsername(groupId, null, userName);
        if (refGroupAccountOperation != null && refGroupAccountOperation.getContentInvisibleTime() != null) {
            contentInvisibleTime = refGroupAccountOperation.getContentInvisibleTime();
        }

        return contentInvisibleTime;
    }
}